﻿/**************************************************************************
创建时间:	2020/5/13 9:43:03    
作	  者:	张存
邮 	  箱:	zhangcunliang@126.com

Copyright (c) zhcunc.cn

描	述：
记	录：
***************************************************************************/
using ASmile.Extend;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ASmile.Win.Controls
{
    public class EditComboBox : ComboBox, IEditDCM
    {
        [Browsable(false)]
        public object ValueItem
        {
            get
            {
                if (SelectedValue != null) return SelectedValue;
                return SelectedIndex;
            }
            set
            {
                if (value == null) return;
                if (ValueMember.IsEmpty())
                {
                    if (int.TryParse(value.ToString(), out int selIndex))
                    {
                        if (Items.Count > selIndex) SelectedIndex = selIndex;
                        return;
                    }
                }
                SelectedValue = value;
                if (DataSource == null)
                {
                    for (int i = 0; i < Items.Count; i++)
                    {
                        SelectedIndex = i;
                        object selObj = Items[i];

                        Type t = selObj.GetType();
                        System.Reflection.PropertyInfo pro = t.GetProperty(ValueMember);
                        if (pro != null)
                        {
                            object val = pro.GetValue(Items[i], null);
                            if (val.Equals(value))
                            {
                                return;
                            }
                        }
                    }
                    if (Items.Count > 0) SelectedIndex = 0;
                }
            }
        }

        [Browsable(false)]
        public object DisplayItem
        {
            get
            {
                return Text;
            }
            set
            {
                for (int i = Items.Count - 1; i >= 0; i--)
                {
                    SelectedIndex = i;
                    if (Text.Equals(value))
                    {
                        return;
                    }
                }
                Text = value?.ToString();
            }
        }

        [Browsable(false)]
        public bool IsValueChanged { get; } = true;

        [Browsable(false)]
        public bool IsDisplayChanged { get; } = true;

        public void SetDefault()
        {
            if (Items.Count > 0)
            {
                this.SelectedIndex = 0;
            }
        }
    }
}